<template>
    <view>
        <u-sticky>
            <view class="bind-machine-search-bar">
                <view class="search-bar-row" style="height: 52px;padding: 0 32rpx;display: flex;align-items: center;">
                    <u-search
                        v-model="searchParams.empName"
                        shape="round" placeholder="人员名称"
                        :actionStyle="{color: '#515a6e'}"
                        :inputStyle="{ height: '36px' }"
                        :clearabled="false"
                        inputAlign="center"
                        @custom="getListRequest"
                        @search="getListRequest"
                    ></u-search>
                </view>
                <view class="search-bar-row" style="height: 44px;">
                    <view class="search-item" @click="onClickWorkshop">
                        <view class="item-gap">{{ searchParams.workshopName || '暂无车间' }}</view>
                        <u-icon name="arrow-down-fill" size="14" color="#515a6e"></u-icon>
                    </view>
                    <view class="search-item" @click="onClickDate">
                        <view class="item-gap">{{ searchParams.belongDate || '日期' }}</view>
                        <u-icon name="arrow-down-fill" size="14" color="#515a6e"></u-icon>
                    </view>
                    <view class="search-item" @click="onScheduleShiftChange">
                        <view class="item-gap">{{ searchParams.scheduleShiftName || '班次' }}</view>
                        <u-icon name="arrow-down-fill" size="14" color="#515a6e"></u-icon>
                    </view>
                    <view class="search-item" @click="onScheduleGroupChange">
                        <view class="item-gap">{{ searchParams.scheduleGroupName || '班组' }}</view>
                        <u-icon name="arrow-down-fill" size="14" color="#515a6e"></u-icon>
                    </view>
                </view>
            </view>
        </u-sticky>
        <view class="operation-container">
            <view class="legend-container" style="margin: 0;">
                <view style="font-size: 26rpx;color: #17233d;">图例:</view>
                <view
                    v-for="(item, index) in legendList"
                    :key="index"
                    class="legend-item"
                    :style="{ display: !item.count ? 'none' : '' }"
                >
                    <view :style="{ background: item.bgColor, display: !item.count ? 'none' : '', width: '24rpx', height: '24rpx' }" class="legend-item-icon"></view>
                    <view>{{ item.text }}</view>
                </view>
            </view>
            <view @click="onEditBtn">
                <u-icon :name="!isEdit ? 'list-dot' : 'checkmark'" size="24"></u-icon>
            </view>
        </view>
        <view class="list-container">
            <view v-show="!tableData.length" class="text-center font-size-14">暂无数据</view>
            <view
                v-for="(empItem, empIndex) in tableData"
                :key="empIndex"
                class="emp-item"
            >
                <view class="flex-between-center" style="height: 72rpx;border-bottom: solid 1rpx #eee;padding-left: 20rpx;">
                    <view class="emp-item-label">
                        <view class="" style="font-size: 30rpx;color: #515a6e;margin-right: 8rpx;border-left: solid 8rpx #2d8cf0;padding-left: 8rpx;">{{empItem.empName}}</view>
                        <view class="emp-item-post-name">{{ empItem.scheduleEmpPostList.length ? empItem.scheduleEmpPostList[0].postName : '' }}</view>
                    </view>
                    <view v-show="isEdit">
                        <u-icon @click="onDeleteEmp(empItem)" name="trash" size="20" color="red"></u-icon>
                    </view>
                </view>
                <view class="emp-item-groups">
                    <view
                        v-for="(postItem, postIndex) in empItem.scheduleEmpPostList"
                        :key="postIndex"
                        class="emp-item-post-container"
                    >
                        <view class="emp-item-post-machine-container">
                            <view
                                v-for="(machineItem, machineIndex) in postItem.scheduleEmpMachineList"
                                :key="machineIndex"
                                class="machine-item"
                                @click.stop="onSetSpinGroupForEmp(empItem, machineItem)"
                            >
                                <view class="machine-item-inner">
                                    <view class="machine-state-icon" :style="{background: setBgColor(machineItem)}"></view>
                                    <view>{{ machineItem.machineName }}</view>
                                    <view v-show="isEdit" class="machine-item-delete" @click.stop="onDeleteMachine(empItem, machineItem)">
                                        <u-icon name="minus-circle-fill" size="20" color="#ed4014"></u-icon>
                                    </view>
                                </view>
                            </view>
                            <view class="machine-item" @click="onAddMachine(empItem, postItem)">
                                <view class="machine-item-inner" style="border-color: #91d5ff;background: #f0faff;">
                                    <u-icon name="plus" size="12" color="#2d8cf0"></u-icon>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="footer-operation-box" style="flex-direction: column;">
                <view class="color2 font-size-14 text-left width-100-percentage margin-bottom-10">
                    <text>共计:  </text>
                    <text style="color: #2d8cf0;margin-left: 4rpx;">{{tableData.length}}</text>
                    <text>人</text>
                </view>
                <u-button :disabled="!searchParams.scheduleShiftId || !searchParams.scheduleGroupId" @click="onAddEmpBtn" class="push-button-style" size="large" text="添加人员" color="#5c6be3"></u-button>
            </view>
        </view>
        <bind-spin-group-modal
            :formData="setSpinGroupData"
            :modalState="bindSpinGroupModalState"
            @confirm="onConfirmOfBindSpinGroupModalState"
            @on-visible-change="onVisibleChangeOfSpinGroupModalState"
        ></bind-spin-group-modal>
        <u-datetime-picker
            :show="showSelectMonthPicker"
            v-model="initTimeVal"
            :closeOnClickOverlay="true"
            mode="date"
            @confirm="onConfirmOfSelectMonthPicker"
            @close="showSelectMonthPicker = false"
            @cancel="showSelectMonthPicker = false"
        ></u-datetime-picker>
        <select-machine-popup
            :selectedData="selectedMachineArr"
            :form-data="searchParams"
            :show="selectMachinePopupState"
            @close="selectMachinePopupState = false"
            @confirm="onConfirmSelectMachineBtn"
        ></select-machine-popup>
    </view>
</template>

<script>
import {
    machineManagerMachinePage,
    systemAuthGetPermissionInfo,
    workforcemanagementScheduleEmpMachineCreate,
    workforcemanagementScheduleEmpMachineDelete,
    workforcemanagementScheduleGroupDeleteEmp,
    workforcemanagementScheduleGroupList,
    workforcemanagementScheduleList, workforcemanagementScheduleShiftByTime,
} from "../../../api";
import {formatDate, tipBar, showLoading, formatTime} from "../../../utils/jk-utils";
    import jkPopup from '../../../jk-components/jk-popup';
    import bindSpinGroupModal from './components/bind-spin-group-modal';
import selectMachinePopup from "../myMachine/components/select-machine-popup";
    export default {
        components: {
            selectMachinePopup,
            bindSpinGroupModal,
            jkPopup
        },
        data() {
            return {
                selectMachinePopupState: false,
                initTimeVal: '',
                legendList: [
                    { count: 0, text: '0人', bgColor: '#c5c8ce' },
                    { count: 1, text: '1人', bgColor: '#19be6b' },
                    { count: 2, text: '2人', bgColor: '#2d8cf0' },
                    { count: 3, text: '3人', bgColor: '#ff9900' },
                    { count: 4, text: '4人及以上', bgColor: '#ed4014' },
                ],
                showSelectMonthPicker: false,
                selectedMachineArr: [],
                isEdit: false,
                bindSpinGroupModalState: false,
                selectProduct: null,
                searchParams: {
                    scheduleId: null,
                    scheduleGroupId: null,
                    scheduleGroupName: '',
                    scheduleShiftId: null,
                    scheduleShiftName: '',
                    belongDate: '',
                    empName: '',
                    workshopId: null,
                    machineNameOrCode: ""
                },
                workshopList: [],
                tableData: [],
                selectMachineItem: {},
                productTaskItem: {},
                ruleForm: {},
                scheduleShiftList: [],
                scheduleGroupList: [],
                setSpinGroupData: {},
                updateEmpItem: {},
                updatePostItem: {}
            };
        },
        methods: {
            onConfirmOfSelectMonthPicker(e) {
                this.showSelectMonthPicker = false;
                this.$set(this.searchParams, 'belongDate', formatDate(e.value));

                this.tableData = [];
                this.$set(this.searchParams, 'scheduleId', null);
                this.$set(this.searchParams, 'scheduleShiftId', null);
                this.$set(this.searchParams, 'scheduleShiftName', '');
                this.scheduleShiftList = [];
                this.$set(this.searchParams, 'scheduleGroupId', null);
                this.$set(this.searchParams, 'scheduleGroupName', '');
                this.scheduleGroupList = [];

                this.getDateScheduleShiftOptionRequest();
            },
            setBgColor(item) {
                let color = '';
                if (!item.scheduleEmpCount) {
                    color = this.legendList.find(x => x.count === 0).bgColor;
                } else if (item.scheduleEmpCount > 3) {
                    color = this.legendList.find(x => x.count === 4).bgColor;
                } else {
                    color = this.legendList.find(x => x.count === item.scheduleEmpCount).bgColor;
                }
                return color;
            },
            onSetSpinGroupForEmp(empItem, machineItem) {
                let machine = JSON.parse(JSON.stringify(machineItem));
                this.setSpinGroupData = {
                    id: machine.id,
                    machineId: machine.machineId,
                    machineCode: machine.machineCode,
                    machineName: machine.machineName,
                    spinGroupList: machine.spinGroupList
                };
                this.bindSpinGroupModalState = true;
            },
            onEditBtn() {
                this.isEdit = !this.isEdit;
                if (this.isEdit) {
                    uni.showToast({
                        title: '编辑模式',
                        icon: 'success'
                    });
                }
            },
            onDeleteMachine(empItem, machineItem) {
                let _this = this;
                uni.showModal({
                    title: '提示',
                    icon: 'error',
                    content: `确定移除"${empItem.empName}"的${machineItem.machineCode}"吗?`,
                    success(res) {
                        if (res.confirm) {
                            workforcemanagementScheduleEmpMachineDelete({}, {
                                id: machineItem.id,
                            }).then(res => {
                                if (res.data.status === 200) {
                                    tipBar('save');
                                    _this.getListRequest();
                                }
                            });

                        }
                    }
                });
            },
            onDeleteEmp(empItem) {
                let _this = this;
                uni.showModal({
                    title: '提示',
                    icon: 'error',
                    content: `确定移除"${empItem.empName}"吗?`,
                    success(res) {
                        if (res.confirm) {
                            workforcemanagementScheduleGroupDeleteEmp({
                                ids: [empItem.id],
                                scheduleEmpExceptionalCaseId: -1,
                                scheduleEmpExceptionalCaseName: '调整'
                            }).then(res => {
                                if (res.data.status === 200) {
                                    tipBar('save');
                                    _this.getListRequest();
                                }
                            });

                        }
                    }
                });
            },
            onConfirmSelectMachineBtn(data) {
                this.selectMachinePopupState = false;
                this.saveMachine(data);
            },
            saveMachine(data) {
                this.updateEmpItem.scheduleEmpPostList.scheduleEmpMachineList = [];
                let arr = data.map(k => {
                    return {
                        machineCode: k.code,
                        machineId: k.id,
                        machineName: k.name
                    }
                })
                let params = {
                    scheduleId: this.searchParams.scheduleId,
                    scheduleGroupId: this.searchParams.scheduleGroupId,
                    scheduleEmpId: this.updateEmpItem.id,
                    schedulePostId: this.updatePostItem.id,
                    machineList: arr,
                };
                workforcemanagementScheduleEmpMachineCreate(params).then(res => {
                    if (res.data.status === 200) {
                        tipBar('save');
                        this.getListRequest();
                    }
                })
            },
            onAddMachine(empItem, postItem) {
                this.selectedMachineArr = postItem ? JSON.parse(JSON.stringify(postItem)).scheduleEmpMachineList : [];
                this.updateEmpItem = JSON.parse(JSON.stringify(empItem));
                this.updatePostItem = JSON.parse(JSON.stringify(postItem));
                this.selectMachinePopupState = true;
            },
            getListRequest() {
                if (!this.searchParams.workshopId || !this.searchParams.scheduleId || !this.searchParams.scheduleGroupId) return false;
                showLoading(true);
                return workforcemanagementScheduleGroupList({
                    workshopId: this.searchParams.workshopId,
                    scheduleId: this.searchParams.scheduleId,
                    scheduleGroupId: this.searchParams.scheduleGroupId,
                    empName: this.searchParams.empName,
                    // workshopId: 18,
                    // scheduleId: 448,
                    // scheduleGroupId: 1309,
                }).then(res => {
                    showLoading(false);
                    if (res.data.status === 200) {
                        if (res.data.res) {
                            const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : { scheduleEmpList: [] };
                            resData.scheduleEmpList ? resData.scheduleEmpList.map(x => {
                                x.totalMachineNum = 0;
                                x.scheduleEmpPostList = x.scheduleEmpPostList || [];
                                x.scheduleEmpPostList.forEach(p => {
                                    p.scheduleEmpMachineList = p.scheduleEmpMachineList || [];
                                });
                                return x;
                            }) : [];
                            this.tableData = resData.scheduleEmpList;
                        }
                    }
                });
            },
            onScheduleGroupChange() {
                if (!this.scheduleGroupList.length) {
                    uni.showToast({
                        title: '无班组数据',
                        icon: 'error'
                    });
                    return;
                }
                let _this = this;
                uni.showActionSheet({
                    itemList: _this.scheduleGroupList.map(x => x.groupName),
                    success(res) {
                        let item = _this.scheduleGroupList[res.tapIndex];
                        _this.tableData = [];
                        _this.$set(_this.searchParams, 'scheduleGroupId', item.id);
                        _this.$set(_this.searchParams, 'scheduleGroupName', item.groupName);
                        _this.getListRequest();
                    }
                });
            },
            onScheduleShiftChange() {
                if (!this.scheduleShiftList.length) {
                    uni.showToast({
                        title: '无班次数据',
                        icon: 'error'
                    });
                    return;
                }

                let _this = this;
                uni.showActionSheet({
                    itemList: _this.scheduleShiftList.map(x => x.shiftName),
                    success(res) {
                        _this.$set(_this.searchParams, 'scheduleId', null);
                        _this.$set(_this.searchParams, 'scheduleGroupId', null);
                        _this.$set(_this.searchParams, 'scheduleGroupName', '');
                        _this.scheduleGroupList = [];
                        let item = _this.scheduleShiftList[res.tapIndex];
                        _this.tableData = [];
                        _this.$set(_this.searchParams, 'scheduleId', item.scheduleId);
                        _this.$set(_this.searchParams, 'scheduleShiftId', item.id);
                        _this.$set(_this.searchParams, 'scheduleShiftName', item.shiftName);
                        _this.scheduleGroupList = item.scheduleGroupList || [];
                    }
                });
            },
            getDateScheduleShiftOptionRequest() {
                if (this.searchParams.workshopId && this.searchParams.belongDate) {
                    return workforcemanagementScheduleList({
                        belongDate: `${this.searchParams.belongDate},${this.searchParams.belongDate}`,
                        workshopId: this.searchParams.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData && resData.length) {
                                this.scheduleShiftList = resData[0].scheduleShiftList || [];
                            }
                        }
                    });
                }
            },
            onClickDate() {
                this.showSelectMonthPicker = true;
            },
            onBackBtn() {
                uni.switchTab({
                    url: '/pages/index/index'
                });
            },
            onConfirmOfBindSpinGroupModalState() {
                this.bindSpinGroupModalState = false;
                this.getListRequest();
            },
            onVisibleChangeOfSpinGroupModalState(e) {
                this.bindSpinGroupModalState = e;
            },
            onAddEmpBtn() {
                let empIdsStr = this.tableData.map(x => x.empId) + '';
                wx.navigateTo({
                    url: `/pages/schedule/empBindMachineBatch/toSelectEmp?workshopId=${this.searchParams.workshopId}&scheduleId=${this.searchParams.scheduleId}&scheduleGroupId=${this.searchParams.scheduleGroupId}&empIds=${empIdsStr}`
                });
            },
            onClickMachine() {
            },
            onClickWorkshop() {
                let _this = this;
                uni.showActionSheet({
                    itemList: _this.workshopList.map(x => x.workshopName),
                    success(res) {
                        _this.tableData = [];
                        _this.$set(_this.searchParams, 'scheduleShiftId', null);
                        _this.$set(_this.searchParams, 'scheduleShiftName', '');
                        _this.scheduleShiftList = [];
                        _this.$set(_this.searchParams, 'scheduleGroupId', null);
                        _this.$set(_this.searchParams, 'scheduleGroupName', '');
                        _this.scheduleGroupList = [];
                        _this.$set(_this.searchParams, 'workshopId', _this.workshopList[res.tapIndex].workshopId);
                        _this.$set(_this.searchParams, 'workshopName', _this.workshopList[res.tapIndex].workshopName);
                        _this.getDateScheduleShiftOptionRequest();
                        _this.getScheduleShiftForTimeRequest();
                    }
                });
            },
            getWorkshopDataRequest() {
                return systemAuthGetPermissionInfo().then(res => {
                    if (res.data.status === 200) {
                        if (!this.searchParams.workshopId) {
                            this.$set(this.searchParams, 'workshopId', res.data.res.workshop.defaultWorkshopId);
                            this.$set(this.searchParams, 'workshopCode', res.data.res.workshop.defaultWorkshopCode);
                            this.$set(this.searchParams, 'workshopName', res.data.res.workshop.defaultWorkshopName);
                        }
                        this.workshopList = res.data.res.workshop.workshops;
                    }
                })
            },
            getScheduleShiftForTimeRequest() {
                if (this.searchParams.workshopId) {
                    return workforcemanagementScheduleShiftByTime({
                        startTime: formatTime(Date.now()),
                        workshopId: this.searchParams.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData) {
                                this.$set(this.searchParams, 'scheduleId', resData.scheduleId);
                                this.$set(this.searchParams, 'scheduleShiftId', resData.id);
                                this.$set(this.searchParams, 'scheduleShiftName', resData.shiftName);
                                this.scheduleGroupList = resData.scheduleGroupList;
                            }
                        }
                    });
                }
            },
            getUserGroupInfoRequest() {
                return systemAuthGetPermissionInfo().then(res => {
                    if (res.data.status === 200) {
                        // 默认用户分配的班组 （缺陷:如果用户默认的班组和排的班组不一致时会出现无法回显的问题）
                        /*if (res.data.res.group.defaultGroupId) {
                            const scheduleGroupItem = this.scheduleGroupList.find(x => x.groupId === res.data.res.group.defaultGroupId) || {};
                            this.$set(this.searchParams, 'scheduleGroupId', scheduleGroupItem.id);
                            this.$set(this.searchParams, 'scheduleGroupName', scheduleGroupItem.groupName);
                        } else {
                            let scheduleGroupItem = this.scheduleGroupList.length ? this.scheduleGroupList[0] : {};
                            this.$set(this.searchParams, 'scheduleGroupId', scheduleGroupItem.id);
                            this.$set(this.searchParams, 'scheduleGroupName', scheduleGroupItem.groupName);
                        }*/

                        // 默认当前班次的第一个班组
                        let scheduleGroupItem = this.scheduleGroupList.length ? this.scheduleGroupList[0] : {};
                        this.$set(this.searchParams, 'scheduleGroupId', scheduleGroupItem.id);
                        this.$set(this.searchParams, 'scheduleGroupName', scheduleGroupItem.groupName);
                    }
                });
            },
            async getDependentData() {
                await this.getWorkshopDataRequest();
                await this.getDateScheduleShiftOptionRequest();
                await this.getScheduleShiftForTimeRequest();
                await this.getUserGroupInfoRequest();
                await this.getListRequest();
            }
        },
        onShow() {
            this.initTimeVal = Date.now();
        },
        onLoad() {
            if (!this.searchParams.belongDate) {
                this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
            }
            this.getDependentData();
        }
    }
</script>
<style scoped lang="scss">
    @import "list";
</style>
